package com.roc.web.action.merinfo;

/**
 * @author zbl
 * @date 2014-08-09
 * 
 * */
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionContext;
import com.roc.bean.MerinfoDetail;
import com.roc.bean.MerinfoSearchBean;
import com.roc.bean.TermBean;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.AuditingItem;
import com.roc.pojo.EsmidinfoMerinfo;
import com.roc.pojo.EsmidinfoTmp;
import com.roc.pojo.Operators;
import com.roc.pojo.OrgBean;
import com.roc.pojo.TReceive;
import com.roc.pojo.TblEditMchtInf;
import com.roc.pojo.Termapply;
import com.roc.service.IAgentService;
import com.roc.service.IMerchantServices;
import com.roc.service.IPagenitionService;


import com.roc.service.IRiskService;
import com.roc.service.ServiceException;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.Utils;
import com.roc.util.constant.AuditingResultCodeType;
import com.roc.util.constant.ConfigMerinfoUtil;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.MerchantStatus;
import com.roc.util.constant.MerinfoStatus;
import com.roc.util.constant.Role;

@Component
@Namespace("/merinfoAlloat")
@SuppressWarnings("all")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class MerinfoAlloatAction extends PaginationBaseAction {
	static Logger logger = Logger.getLogger(MerinfoAlloatAction.class);

    
	
	@Autowired
	IMerchantServices merinfoService;
	@Autowired
	IPagenitionService pagenitionService;
	@Autowired
	IPageService pageService1;
	@Autowired
	IRiskService  riskService;

	private TblEditMchtInf merinfo; // 商户临时表
	private String isDetail; // 查看详情
	private MerinfoAlloatSearchCondtion alloatSearchCondition;
	private MerinfoDetail merinfoDetail; // 商户详情

	private String[] transTypes;// 交易类型
	private List<Operators> riskList = new ArrayList<Operators>();
	private String merInfoIdList;
	
	
	/**
	 * 跳转商户分配风控人员选择
	 * */
	@Action(value="alloat",results={@Result(name=SUCCESS,location="/pages/merinfo/merinfoAlloatjsp.jsp")})
	public String alloat(){
		try {
			//初始化风控人员
			riskList = riskService.queryrisk();
		} catch (Exception e) {
			addActionError("加载风控人员信息失败，请联系客服人员");
			logger.error(e.getMessage(),e);
		}
		return SUCCESS;
	}
	/**
	 * 跳转商户分配主页面
	 * */
	@Action(value="merinfoAlloat",results={@Result(name=SUCCESS,location="/pages/merinfo/merinfoAlloat.jsp"),
			@Result(name = "error", location = "/error.jsp")})
	public String returnCollarPiecesJsp(){
		try {
			Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			if(op.getRoleType().equals(Role.AGENT.getCode())&&!"sdsyb".equals(op.getAccountNo())) {
				addActionError("当前登录账号无权限访问!!!");
				return ERROR;
			}
			alloat();
		} catch (Exception e) {
			logger.error("跳转到商户分配出错");
		}
		return SUCCESS;
	}
	
	/**
	 * 商户分配查询
	 * @return
	 */
	@Action(value="queryMerinfoAlloat",results={@Result(name=SUCCESS,location="/pages/merinfo/merinfoAlloat.jsp"),
			@Result(name = ERROR, location = "/error.jsp")})
	public String checkCollarPieces(){
		 Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			if(op.getRoleType().equals(Role.AGENT.getCode())&&!"sdsyb".equals(op.getAccountNo())) {
				addActionError("当前登录账号无权限访问!!!");
				return ERROR;
			}
		 try {
        	 alloat();
        	 if(alloatSearchCondition==null){
					alloatSearchCondition=(MerinfoAlloatSearchCondtion)getSearchConditionFromSession();
					if(alloatSearchCondition==null){
						alloatSearchCondition=new MerinfoAlloatSearchCondtion();
					}
			}
					
			if(op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode()) || 
			    op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode())  ){
				alloatSearchCondition.setOrgCode(op.getOrgCode());//当前查询人员所属机构
				alloatSearchCondition.setMerinfoFlag(4);//待审核状态
				alloatSearchCondition.setRoleId(op.getRoleType());// 角色
			//	alloatSearchCondition.setRkopId(String.valueOf(op.getId()));//操作员id
				queryMerinfoAlloat();
					}
         }catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
			return ERROR;
		}
		return SUCCESS;
		
	}
	/**
	 * 商户释放
	 * @return
	 */
	@Action(value="merinfoRelease")
	public String saveCollarPieces(){
		Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		PrintWriter pw = null;
		JSONObject json = new JSONObject();
		try {
			
			
			getResponse().setCharacterEncoding("utf-8");
			pw = getResponse().getWriter();
			
			logger.info(op.getRealName()+"开始释放商户,商户号是："+merInfoIdList);
			List<String> rsList = merinfoService.merinfoRelease(op,merInfoIdList);
			
			json.put("rsList", rsList);
			pw.write(json.toString());
						
		} catch (Exception e) {
			logger.error("商户释放异常");
			logger.error(e.getMessage(),e);
//			json.put("msg", "领取异常");
//			json.put("boo", false);
//			pw.write(json.toString());
		}finally{
			if(pw != null){
				pw.close();
			}
		}
		
		return null;
	}
	 public void  queryMerinfoAlloat() throws Exception{
			try {
				alloat();
				int rows=pagenitionService.countSQL(alloatSearchCondition);
				if(rows>0){
					searchRsList=pagenitionService.findAllSQL(alloatSearchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
				}
				List<MerinfoSearchBean> msList = new ArrayList<MerinfoSearchBean>();	
				if(searchRsList.size()>0 && searchRsList!=null){			
					Iterator iterator=searchRsList.iterator();
					while (iterator.hasNext()) {
						Object[] obj= (Object[])iterator.next();
						MerinfoSearchBean msb = new MerinfoSearchBean();
						msb.setMid(Constance.Null2EmptyTrim(obj[0]));  //商户号
						msb.setMerName(Constance.Null2EmptyTrim(obj[1])); //商户简称
						msb.setMerBrName(Constance.Null2EmptyTrim(obj[2]));//商户注册名称
						msb.setMerKind(Constance.Null2EmptyTrim(obj[3]));//机构名称
						msb.setPerName(Constance.Null2EmptyTrim(obj[4])); //商户联系人
						String phone=Constance.Null2EmptyTrim(obj[5]);//联系人手机号
						
							msb.setPerPhone(phone);//手机号
						
						msb.setInterContact(Constance.Null2EmptyTrim(obj[6])); //法人
						String cardNo=Constance.Null2EmptyTrim(obj[7]);//法人证件号
						
						
							msb.setCardNo(cardNo);//证件号
						
						msb.setFlagCode(Constance.Null2EmptyTrim(obj[8]));//营业执照
						msb.setAddr(Constance.Null2EmptyTrim(obj[9])); //地址
						msb.setFlag(MerinfoStatus.getName(Constance.Null2EmptyTrim(obj[10])));//状态
						msb.setCompanyName(Constance.Null2EmptyTrim(obj[11])); //所属分公司
						msb.setOneAgentName(Constance.Null2EmptyTrim(obj[12]));//所属一级代理
						msb.setAgentId(Constance.Null2EmptyTrim(obj[13]));//直属代理商
						
						msb.setRsvl(Constance.Null2EmptyTrim(obj[14]));//结算银行账户名称
						String account=Constance.Null2EmptyTrim(obj[15]);
						/*if(account!=null && account.length()>4){
							msb.setRsvl3(account.substring(0, 4)+"****"+account.substring(account.length()-4));//结算银行账户
						}else{*/
							msb.setRsvl3(account);//结算银行账户
						//}
						msb.setAmount1(Constance.Null2EmptyTrim(obj[16]));//结算银行名称
						msb.setAmount2(Constance.Null2EmptyTrim(obj[17]));//联行号
						//String[] cycleList=merinfoService.queryMchtBizDealArray(msb.getMid(),false,true);//根据商户查询结算周期
						//msb.setMerCycle(cycleList);
						msb.setEngName(Constance.Null2EmptyTrim(obj[18]));
						msList.add(msb);
					}
				}
				this.setTotalPage(this.calcuTotalPage(rows));
				getRequest().setAttribute(SEARCH_RS_LIST, msList);
				getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
				getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
				setSearchToConditionSession(alloatSearchCondition);
				
			} catch (ServiceException e) {
				
				logger.error(e.getMessage(),e);
				addActionError(e.getMessage());
				
			}
		}
	 
	 /**
		 * 商户分配
		 * @return merinfoAlloat
		 */
		@Action(value="merinfoAlloat1")
		public String merinfoAlloat(){
			Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			String name = null;
			if (alloatSearchCondition.getAlloatName() == null
					|| alloatSearchCondition.getAlloatName().trim().length() == 0) {
				addActionError("请输入分配人员！");
				return ERROR;
			} else {
				name = alloatSearchCondition.getAlloatName();
			}
			
			PrintWriter pw = null;
			JSONObject json = new JSONObject();
			try {
				getResponse().setCharacterEncoding("utf-8");
				pw = getResponse().getWriter();
				
				logger.info(op.getRealName()+"开始分配商户,商户号是："+merInfoIdList);
				Map<String,Object> resultMap = merinfoService.merinfoAlloat(alloatSearchCondition,op,merInfoIdList);
				
				json.put("resultMap", resultMap);
				pw.write(json.toString());
							
			} catch (Exception e) {
				logger.error("商户分配异常");
				logger.error(e.getMessage(),e);
			}finally{
				if(pw != null){
					pw.close();
				}
			}
			
			return null;
		}
	
	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE + "";
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.roc.page.PaginationBaseAction#getSearchConditionFromSession()
	 */
	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (MerinfoAlloatSearchCondtion) getSession().getAttribute(SEARCH_SESSION_MERINFO_ALLOAT_QUERY);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.roc.page.PaginationBaseAction#getSearchConditionFromSubClass()
	 */
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass() throws Exception {
		// TODO Auto-generated method stub
		return alloatSearchCondition;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.roc.page.PaginationBaseAction#setSearchConditionToSubClass(com.roc.
	 * page.BaseSearchCondition)
	 */
	@Override
	protected void setSearchConditionToSubClass(BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.roc.page.PaginationBaseAction#setSearchToConditionSession(com.roc.
	 * page.BaseSearchCondition)
	 */
	@Override
	protected void setSearchToConditionSession(BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_MERINFO_ALLOAT_QUERY, searchCondition);
	}



	public MerinfoAlloatSearchCondtion getSearchCondition() {
		return alloatSearchCondition;
	}

	public void setSearchCondition(MerinfoAlloatSearchCondtion searchCondition) {
		this.alloatSearchCondition = searchCondition;
	}

	public MerinfoDetail getMerinfoDetail() {
		return merinfoDetail;
	}

	public void setMerinfoDetail(MerinfoDetail merinfoDetail) {
		this.merinfoDetail = merinfoDetail;
	}


	public String[] getTransTypes() {
		return transTypes;
	}

	public void setTransTypes(String[] transTypes) {
		this.transTypes = transTypes;
	}


	public String getIsDetail() {
		return isDetail;
	}

	public void setIsDetail(String isDetail) {
		this.isDetail = isDetail;
	}

	public String getMerInfoIdList() {
		return merInfoIdList;
	}

	public void setMerInfoIdList(String merInfoIdList) {
		this.merInfoIdList = merInfoIdList;
	}
	public TblEditMchtInf getMerinfo() {
		return merinfo;
	}
	public void setMerinfo(TblEditMchtInf merinfo) {
		this.merinfo = merinfo;
	}
	public MerinfoAlloatSearchCondtion getAlloatSearchCondition() {
		return alloatSearchCondition;
	}
	public void setAlloatSearchCondition(
			MerinfoAlloatSearchCondtion alloatSearchCondition) {
		this.alloatSearchCondition = alloatSearchCondition;
	}
	public List<Operators> getRiskList() {
		return riskList;
	}
	public void setRiskList(List<Operators> riskList) {
		this.riskList = riskList;
	}
	
	

}
